﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using NPOI.XSSF.UserModel;
using Produce.Application.DTO.Input;
using Produce.Application.DTO.Output;
using Produce.Application.Services;
using Produce.Domain.Entities;
using Produce.Result;
using Qiniu.Http;
using Qiniu.Storage;
using Qiniu.Util;
using Yitter.IdGenerator;




namespace Produce.Api.Controllers
{
    /// <summary>
    /// 生产模型控制器
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class ProduceModelController : ControllerBase
    {
        private readonly IProduceModelAppService service;
        private readonly ILogger<ProduceModelController> logger;
        /// <summary>
        /// 注入构造函数
        /// </summary>
        /// <param name="service"></param>
        /// <param name="logger"></param>
        public ProduceModelController(IProduceModelAppService service, ILogger<ProduceModelController> logger)
        {
            this.service = service;
            this.logger = logger;
        }

        /// <summary>
        /// 添加工单
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpPost]
        public ApiResult<int> AddWorkorder(AddWorkorderInput input)
        {
            logger.LogInformation($"{input.CreatedBy}进行了添加工单的操作,在{DateTime.Now}");
            return service.AddWorkorder(input);
        }
        /// <summary>
        /// 获取工单
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet]
        public ApiPaging<WorkorderOutput> GetWorkOrder([FromQuery] GetWorkorderInput input)
        {
            logger.LogInformation($"{input.CreatedName}进行了获取工单的操作,在{DateTime.Now}");
            return service.GetWorkOrder(input);
        }
        /// <summary>
        /// 上传文件(七牛云)
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost] // 指定该方法处理 HTTP POST 请求
        public async Task<IActionResult> UploadImages(IFormFile file) // 定义一个异步方法，接收一个文件类型的参数
        {
            if (file == null || file.Length == 0) // 检查文件是否为空或文件大小
            {
                return BadRequest("文件不能为空");
            }

            string saveKey = "Pic/" + file.FileName; // 设置上传文件保存的路径和文件名,可以随便输入 不用创建可自动生成
            string bucket = "xyf-img"; // 七牛云存储空间名称   七牛云仓库名称
            Mac mac = new Mac("s93QzD2kkEcPpdLa4fHcJpxFA4ULq0C01udjmtJN", "aR3LQgh67jWpHDF-2sTcMSBWuTuwiUhdglmLAffF"); // 替换为您七牛云账号的访问密钥和密钥

            // 设置上传策略
            PutPolicy putPolicy = new PutPolicy();
            putPolicy.Scope = bucket + ":" + saveKey; // 设置 Scope 为具体的文件路径，即指定存储空间和保存路径

            // 创建上传凭证
            string token = Auth.CreateUploadToken(mac, putPolicy.ToJsonString()); // 生成上传凭证，凭证包含了上传策略信息

            // 配置上传管理器
            Config config = new Config();
            config.Zone = Zone.ZONE_CN_North; // 设置上传区域，这里是华北区域   自己选的区域,这个是华北,别的自己搜一下
            config.UseHttps = true; // 使用 HTTPS 进行上传
            config.UseCdnDomains = true; // 使用 CDN 域名加速上传
            config.ChunkSize = ChunkUnit.U512K; // 设置分块上传的块大小

            // 实例化表单上传对象
            FormUploader target = new FormUploader(config);

            // 上传文件
            HttpResult result = target.UploadStream(file.OpenReadStream(), saveKey, token, null); // 调用上传方法，上传文件流，传入保存路径和上传凭证

            // 检查上传结果
            if (result.Code == 200) // 判断上传是否成功（返回状态码200表示成功）
            {
                return Ok(file.FileName); // 返回200响应，上传成功，返回文件名
            }
            else
            {
                return BadRequest("上传失败：" + result.Text); // 如果上传失败，返回400错误响应，包含错误信息
            }
        }

        /// <summary>
        /// 修改工单
        /// </summary>ss
        /// <param name="input"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpPut]
        public ApiResult<int> UploadWorkorder(UpdateWorkorderInput input)
        {
            logger.LogInformation($"{input.CreatedBy}进行了修改工单的操作,在{DateTime.Now}");
            return service.UploadWorkorder(input);
        }
        /// <summary>
        /// 删除工单
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpPost]
        public ApiResult<int> DeleteWorkorder(long id)
        {
            //logger.LogInformation($"{output.CreatedBy}进行了删除工单的操作,在{DateTime.Now}");
            return service.DeleteWorkorder(id);
        }

        /// <summary>
        /// 导出工单到Excel
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult ExportWorkOrderToExcel([FromQuery] GetWorkorderInput input)
        {
            logger.LogInformation($"{input.CreatedName}进行了导出工单的操作,在{DateTime.Now}");

            // 复用现有的获取工单接口获取数据
            var result = service.GetWorkOrder(input);

            if (!result.Success || result.PageDate == null || result.PageDate.Count == 0)
            {
                return File(new byte[0], "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "空工单数据.xlsx");
            }

            // 文件名和内容类型
            string fileName = $"工单数据导出_{DateTime.Now:yyyyMMddHHmmss}.xlsx";
            string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

            // 创建Excel工作簿
            using (var workbook = new XSSFWorkbook())
            {
                var sheet = workbook.CreateSheet("工单数据");

                // 创建表头
                var headerRow = sheet.CreateRow(0);
                headerRow.CreateCell(0).SetCellValue("工单编号");
                headerRow.CreateCell(1).SetCellValue("生产类型");
                headerRow.CreateCell(2).SetCellValue("客户");
                headerRow.CreateCell(3).SetCellValue("产品");
                headerRow.CreateCell(4).SetCellValue("生产线");
                headerRow.CreateCell(5).SetCellValue("工艺路线");
                headerRow.CreateCell(6).SetCellValue("状态");
                headerRow.CreateCell(7).SetCellValue("进度");
                headerRow.CreateCell(8).SetCellValue("生产数量");
                headerRow.CreateCell(9).SetCellValue("开始时间");
                headerRow.CreateCell(10).SetCellValue("结束时间");
                headerRow.CreateCell(11).SetCellValue("创建人");
                headerRow.CreateCell(12).SetCellValue("创建时间");

                // 填充数据
                int rowIndex = 1;
                foreach (var item in result.PageDate)
                {
                    // 添加日志记录产品名称
                    logger.LogInformation($"导出工单数据 - ID: {item.Id}, 产品ID: {item.Masterdata}, 产品名称: {item.ProductName}");

                    var dataRow = sheet.CreateRow(rowIndex++);
                    dataRow.CreateCell(0).SetCellValue(item.Code ?? string.Empty);
                    dataRow.CreateCell(1).SetCellValue(item.ProductionType ?? string.Empty);
                    dataRow.CreateCell(2).SetCellValue(item.CustomerName ?? string.Empty);
                    dataRow.CreateCell(3).SetCellValue(item.ProductName ?? string.Empty); // 确保使用ProductName而非Masterdata
                    dataRow.CreateCell(4).SetCellValue(item.LineName ?? string.Empty);
                    dataRow.CreateCell(5).SetCellValue(item.OperationName ?? string.Empty);
                    dataRow.CreateCell(6).SetCellValue(item.State ?? string.Empty);
                    dataRow.CreateCell(7).SetCellValue(item.Progress ?? string.Empty);
                    dataRow.CreateCell(8).SetCellValue(item.ProductionCount?.ToString() ?? string.Empty);
                    dataRow.CreateCell(9).SetCellValue(item.BeginTime?.ToString("yyyy-MM-dd HH:mm:ss") ?? string.Empty);
                    dataRow.CreateCell(10).SetCellValue(item.EndTime?.ToString("yyyy-MM-dd HH:mm:ss") ?? string.Empty);
                    dataRow.CreateCell(11).SetCellValue(item.CreatedBy ?? string.Empty);
                    dataRow.CreateCell(12).SetCellValue(item.CreatedAt?.ToString("yyyy-MM-dd HH:mm:ss") ?? string.Empty);
                }

                // 自动调整列宽
                for (int i = 0; i < 13; i++)
                {
                    sheet.AutoSizeColumn(i);
                }

                // 将工作簿写入字节数组
                using (var ms = new MemoryStream())
                {
                    workbook.Write(ms);
                    var bytes = ms.ToArray();

                    // 返回文件
                    return File(bytes, contentType, fileName);
                }
            }
        }
    }
}
